# 1. Import  standard lib

from flask_wtf import FlaskForm, RecaptchaField

from wtforms import (
	StringField,
	TextField,
	TextAreaField,
	PasswordField,
	BooleanField,
	ValidationError
	)
	
from wtforms.validators import DataRequired, Length, EqualTo, URL


# 2. Used for query user data

from blog.models import User


"""
	`form` used to : output a html tag, EX: <input type='text' ...>, <input type='password' ...>
	
	step1: Form-class define property `StringField | PasswordField` as `html type: 'text | password`
	step2: View_route method Init the `form_instance`
	setp3: Html file tag `<form action='view_route_method` ...>` , use to Form_instance by Jinja2 `{% %} | {{ }}`

"""


class OpenIDForm(FlaskForm):
	""" OpenID Form """
	
	oepnid_url = StringField('OpenID RUL', validators=[DataRequired(),URL()])


class PostForm(FlaskForm):
	""" PostForm """
	
	title = StringField('Title', validators=[DataRequired(), Length(max=255)])
	text = TextAreaField('Content', validators=[DataRequired()])


class RegisterForm(FlaskForm):
	""" Register Form"""
	
	username = StringField('Username', validators=[DataRequired(), Length(max=255)])
	password = PasswordField('Password', validators=[DataRequired(), Length(min=6)])
	confirm = PasswordField('Repeat Password', validators=[DataRequired(), EqualTo('password', message='Must match')])
	accept_tos = BooleanField('Agree')
	
	def validator(self):	
	
		# `user` from to query database
		user = User.query.filter_by(username=self.username.data).first()
		# Check the user whether already exist.
		if user:
			self.username.errors.append('User with that name already exists.')
			return False
		
		return True
		

class LoginForm(FlaskForm):
	""" Login Form """
	
	username = StringField('Username', validators=[DataRequired(), Length(max=64)])
	password = PasswordField('Password', validators=[DataRequired(), Length(min=6)])
	remember = BooleanField("Remember Me")


	def validator(self):
		
		#: `user` from to query database
		user = User.query.filter_by(username=self.username.data).first()
		#: Check the username whether right
		if not user:
			self.username.errors.append('User not exsit')
			return False
		
		#: Check the user password whether exist
		if not user.check_password(self.password.data):
			self.password.errors.append('Password is error')
			return False
		
		# if not user.check_password(self.password.data):
		#	self.username.errors.append('Password error')
		#	return False
		
		return True


class CommentForm(FlaskForm):
	""" Form vaildator for comment """

	# SET some field(InputBox) for enter the data.
	# Patam valildators: a validator object list
	# StringField('Name', ) <=> CommentForm_ins.name.lable
	# CommentForm_ins.name.data ==> ex: 'FROG'

	name = StringField('Name',validators=[DataRequired(), Length(max=255)])	
	text = TextField(u'Comment', validators=[DataRequired()])
